package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.po.SysJob;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.Date;
import java.util.List;

@Mapper
public interface SysJobMapper extends BaseMapper<SysJob> {

    @Select(value = "select * from sys_job where server_key = #{serverKey} and ( status = 1 or (status = 2 and retry_count < #{maxRetryCount} and retry_time < #{nowTime})) order by priority desc limit #{maxSize}")
    public List<SysJob> getJobList(@Param("serverKey") Long serverKey, @Param("maxSize") int maxSize, @Param("maxRetryCount") int maxRetryCount, @Param("nowTime") Date nowTime);

    @Update(value = "update sys_job set server_key = #{serverKey} where MOD(CRC32(id), #{size}) = #{index} and server_key is null")
    public void updateJobServerKey(@Param("size") int size, @Param("index") int index, @Param("serverKey") Long serverKey);

    @Update(value = "update sys_job set server_key = #{targetServerKey} where MOD(CRC32(id), #{size}) = #{index} and server_key = #{sourceServerKey} and ( status = 1 or (status = 2 and retry_count < #{maxRetryCount}))")
    public void updateJobServerKeyToOther(@Param("size") int size, @Param("index") int index, @Param("sourceServerKey") Long sourceServerKey, @Param("targetServerKey") Long targetServerKey, @Param("maxRetryCount") int maxRetryCount);

    @Select(value = "select * from sys_job where status = 3 or (status = 2 and retry_count = #{maxRetryCount}) order by create_time asc limit #{maxSize}")
    public List<SysJob> getFinishJobs(@Param("maxSize") int maxSize, @Param("maxRetryCount") int maxRetryCount);
}